//
//  ConversationListViewController.m
//  TIMChat
//
//  Created by wilderliao on 16/2/16.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ConversationListViewController.h"

#import "ConversationListTableViewCell.h"
#import "MHConversationListViewModel.h"
//#import "ConversationHeaders.h"
#import "MHMessageListHeader.h"
#import "MHIMMessageTransferHelper.h"
#import <WZLBadge/UIView+WZLBadge.h>
#import "MHAttributeModel.h"
#import "MHMessageNotification.h"
#import "MHNewMemberMessage.h"
#import <WZLBadge/UITabBarItem+WZLBadge.h>
#import "MHTabBarController.h"
#import "MHMHPushHelper.h"



#define kRightItemOffset CGPointMake(-6, 4)

#define kTabbarItemOffset CGPointMake(0, 3)
@interface ConversationListViewController ()
{
    
}
@property(nonatomic, strong) MHConversationListViewModel *viewModel;
@property(nonatomic, strong) MHMessageListHeader *listHeader;
@end

@implementation ConversationListViewController
@dynamic viewModel;
- (void)dealloc
{
#warning 处理问题
//    [self.KVOController unobserveAll];
}

//初始化
-(instancetype)initWithViewModel:(MHViewModel *)viewModel
{
    self =  [super initWithViewModel:viewModel];
    if (self) {
        IMAConversationManager *mgr = [IMAPlatform sharedInstance].conversationMgr;
        _conversationList = [mgr conversationList];
        
        self.listHeader;
        __weak ConversationListViewController *ws = self;
        mgr.conversationChangedCompletion = ^(IMAConversationChangedNotifyItem *item) {
            [ws onConversationChanged:item];
        };
        
        [self showTabbarDotView];
        self.KVOController = [FBKVOController controllerWithObserver:self];
        [self.KVOController observe:[IMAPlatform sharedInstance].conversationMgr keyPath:@"unReadMessageCount" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
            [ws onUnReadMessag];
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [ws onUnReadMessag];
        });
        
    }
    return self;
}
//-(void)initialize
//{
//    [super initialize];
//    [self configOwnViews];
//}
- (void)addHeaderView
{
}
- (void)addFooterView
{
    
}

- (BOOL)hasData
{
    BOOL has = _conversationList.count != 0;
    return has;
}

- (void)addRefreshScrollView
{
    _tableView = [[SwipeDeleteTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.frame = self.view.bounds;
//    _tableView.height = self.view.bounds.size.height + 5;
//    _tableView.style = UITableViewStyleGrouped;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = kClearColor;
    _tableView.scrollsToTop = YES;
    [self.view addSubview:_tableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [_tableView setTableFooterView:v];
    
    _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
//    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 5, 0);
    self.refreshScrollView = _tableView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"会话";
    [self pinHeaderView];
    [self showTabbarDotView];
//    [[UITabBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]]];
//    [IMAPlatform sharedInstance].conversationMgr.unReadMessageCoun
    
//    TIMFriendProfileOption * option = [[TIMFriendProfileOption alloc] init];
//    option.friendFlags = 0xffff;
//    TIMUserProfile * profile = [[TIMUserProfile alloc] init];
//    profile.nickname = @"许正";
//    //    profile.allowType = TIM_FRIEND_ALLOW_ANY;
//    //    profile.faceURL = @"https://my face url";
//    //    profile.selfSignature = [NSData dataWithBytes:"1234" length:4];
//    //    profile.gender = TIM_GENDER_MALE;
//    //    profile.birthday = 12345;
//    //    profile.location = [NSData dataWithBytes:"location" length:8];
//    //    profile.language = 1;
//    [[TIMFriendshipManager sharedInstance] modifySelfProfile:option profile:profile succ:^() {
//        NSLog(@"Set Profile Succ");
//    } fail:^(int code, NSString * err) {
//        NSLog(@"Set Profile fail: code=%d err=%@", code, err);
//    }];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBar.translucent = NO;
//    [self showTabbarDotView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [[IMAPlatform sharedInstance].conversationMgr releaseChattingConversation];
}

- (void)addSearchController
{
}

-(MHMessageListHeader *)listHeader
{
    if (!_listHeader) {
        _listHeader = [MHMessageListHeader mh_viewFromXib];
         __weak __typeof(self)weakSelf = self;
        [_listHeader.collectionButton bk_whenTapped:^{
            [weakSelf.viewModel.pushToAttriCommand execute:nil];
            [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHAttributeModel class])];
        }];
        
        [_listHeader.aboutMeButton bk_whenTapped:^{
            [weakSelf.viewModel.releationToMeCommand execute:nil];
            [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHMessageNotification class])];
        }];
        
        
        [_listHeader.systemMessageButton bk_whenTapped:^{
            [weakSelf.viewModel.pushToNewMemberCommand execute:nil];
//            _listHeader.systemSub.text = @"暂无系统消息";
            [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHNewMemberMessage class])];
        }];
        [_listHeader.systemMessageCell bk_whenTapped:^{
            
            [weakSelf.viewModel.pushToSystemMeCommand execute:nil];
            weakSelf.listHeader.systemSub.text = @"暂无系统消息";
            [[MHIMMessageTransferHelper sharedInstance] resetAllreadWithKey:NSStringFromClass([MHPushModel class])];
//            [weakSelf.viewModel.pushToSystemMeCommand execute:nil];
        }];
        
        @weakify(self);
        [RACObserve([MHIMMessageTransferHelper sharedInstance],unReadAttriMessage) subscribeNext:^(NSNumber *unreadNumber) {
            @strongify(self);
            int unread = [unreadNumber intValue];
            if (unread > 0) {
                [self.listHeader.collectionButton.imageView showBadgeWithStyle:WBadgeStyleRedDot value:100 animationType:WBadgeAnimTypeNone];
                self.listHeader.collectionButton.imageView.badgeCenterOffset = kRightItemOffset;
                //            [self showTabbarDotView];
            }else
            {
                [self.listHeader.collectionButton.imageView clearBadge];
            }
            [self showTabbarDotView];
        }];
        
        [RACObserve([MHIMMessageTransferHelper sharedInstance],unReadbNewMemberMessage) subscribeNext:^(NSNumber *unreadNumber) {
            int unread = [unreadNumber intValue];
            if (unread > 0) {
                [self.listHeader.systemMessageButton.imageView showBadgeWithStyle:WBadgeStyleRedDot value:100 animationType:WBadgeAnimTypeNone];
                self.listHeader.systemMessageButton.imageView.badgeCenterOffset = kRightItemOffset;
                
            }else
            {
                [self.listHeader.systemMessageButton.imageView clearBadge];
            }
            [self showTabbarDotView];
            
        }];
        
        [RACObserve([MHIMMessageTransferHelper sharedInstance],unReadRecentMessage) subscribeNext:^(NSNumber *unreadNumber) {
            @strongify(self);
            int unread = [unreadNumber intValue];
            if (unread > 0) {
                [self.listHeader.aboutMeButton.imageView showBadgeWithStyle:WBadgeStyleRedDot value:100 animationType:WBadgeAnimTypeNone];
                self.listHeader.aboutMeButton.imageView.badgeCenterOffset = kRightItemOffset;
                
            }else
            {
                [self.listHeader.aboutMeButton.imageView clearBadge];
            }
            [self showTabbarDotView];
        }];
        
//        @weakify(self);
        [RACObserve([MHIMMessageTransferHelper sharedInstance], unReadbSystemMessage) subscribeNext:^(NSNumber *number) {
            @strongify(self);
            int unRed = [number intValue];
            [self showTabbarDotView];
            self.listHeader.unReadBadge.hidden = unRed <= 0;
           
            [self.listHeader.unReadBadge setTitle:[NSString stringWithFormat:@"%@", unRed > 99 ? @"99+":[NSString stringWithFormat:@"%d",unRed]] forState:UIControlStateNormal];
//            [self.listHeader.unReadBadge setTitle: forState:]];
//            [[XGPush defaultManager] setXgApplicationBadgeNumber: [IMAPlatform sharedInstance].conversationMgr.unReadTotalMessageCount];
            [[XGPush defaultManager] setBadge:[IMAPlatform sharedInstance].conversationMgr.unReadTotalMessageCount];
        }];
        
        [[MHNotificationCenter rac_addObserverForName:MHPushTextNotification object:nil] subscribeNext:^(NSNotification *note) {
            @strongify(self);
            NSString *pushContent  =  note.object;
            self.listHeader.systemSub.text = pushContent;
            
        }];
    }
    return _listHeader;
}
- (void)configOwnViews
{
    
}




- (void)onConversationChanged:(IMAConversationChangedNotifyItem *)item
{
//    [s]
    
    switch (item.type)
    {
        case EIMAConversation_SyncLocalConversation:
        {
            [self reloadData];
        }
            
            break;
        case EIMAConversation_BecomeActiveTop:
        {
            [self.tableView beginUpdates];
            [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:item.index inSection:0] toIndexPath:[NSIndexPath indexPathForRow:item.toIndex inSection:0]];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_NewConversation:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:0];
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_DeleteConversation:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:0];
            [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_Connected:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:0];
            [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_DisConnected:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:0];
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_ConversationChanged:
        {
            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            
            [self.tableView endUpdates];
        }
            break;
        default:
            
            break;
    }
    [MHNotificationCenter postNotificationName:MHReloadFirstPageReloadDataNotification object:nil];
    
}
- (void)onRefresh
{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self reloadData];
        });
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 122 + 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MHMessageListHeader *header = self.listHeader;
    return header;
}

- (void)onUnReadMessag
{
    
    [self showTabbarDotView];
}

-(void) showTabbarDotView
{
    [self.navigationController.tabBarItem clearBadge];
     MHTabBarController *tabbar =   [AXAppDelegate sharedDelegate].window.rootViewController;
//    [self.navigationController.tabBarItem.badge removeFromSuperview];

    NSInteger unRead = [IMAPlatform sharedInstance].conversationMgr.unReadMessageCount + [MHIMMessageTransferHelper sharedInstance].unReadbSystemMessage;
    UINavigationController *nav = [tabbar.tabBarController.viewControllers objectAtIndex:1];
    if (unRead > 0) {
        
        NSInteger unRead = [IMAPlatform sharedInstance].conversationMgr.unReadMessageCount + [MHIMMessageTransferHelper sharedInstance].unReadbSystemMessage;
        [nav.tabBarItem showBadgeWithStyle:WBadgeStyleNumber value:unRead animationType:0];
        nav.tabBarItem.badgeCenterOffset = kTabbarItemOffset;
        nav.tabBarItem.badge.borderColor = [UIColor whiteColor];
        nav.tabBarItem.badge.borderWidth = 1.0f;
    }else
    {
       
        if (tabbar) {
            
            if ([MHIMMessageTransferHelper sharedInstance].unReadRecentMessage > 0 || [MHIMMessageTransferHelper sharedInstance].unReadbNewMemberMessage > 0 || [MHIMMessageTransferHelper sharedInstance].unReadAttriMessage > 0) {
                [nav.tabBarItem showBadgeWithStyle:WBadgeStyleRedDot value:0 animationType:0];
                nav.tabBarItem.badge.size = CGSizeMake(8, 8);
                nav.tabBarItem.badge.borderColor = [UIColor whiteColor];
                nav.tabBarItem.badge.borderWidth = 0.0f;
                nav.tabBarItem.badge.cornerRadius = 4;
                nav.tabBarItem.badge.masksToBounds = YES;
                nav.tabBarItem.badge.badgeBgColor = [UIColor redColor];
                nav.tabBarItem.badgeCenterOffset = kTabbarItemOffset;
//                [self.navigationController.tabBarItem.badge sizeToFit];
            }else
            {
                [self.navigationController.tabBarItem clearBadge];
            }
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
    if ([conv conversationType] != TIM_C2C ) {
        return 0;
    }else
    {
//        IMAUser *user = [[IMAPlatform sharedInstance] getReceiverOf:conv];
//        [MHHTTPService sharedInstance].currentUser.userId;
        if ([[conv showTitle] isEqualToString:[NSString stringWithFormat:@"%d",[MHHTTPService sharedInstance].currentUser.userId]] || [[conv showTitle] isEqualToString:MH_IM_MANAGERIDENTIFY]) {
            return 0;
        }else
        {
              return [conv showHeight];
        }

    }
//    return [conv showHeight];
//     return [conv showHeight];
    
//    return [conv showHeight]
//    return [conv showHeight];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_conversationList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
    NSString *reuseidentifier = [conv showReuseIndentifier];
    [conv attributedDraft];
    id<IMAConversationShowAble> tempCon = [[[IMAPlatform sharedInstance].conversationMgr conversationList] objectAtIndex:indexPath.row];
    [tempCon attributedDraft];
    
    ConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
    if (!cell)
    {
        cell = [[[conv showCellClass] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
    }
    cell.masksToBounds = YES;
    [cell configCellWith:conv];
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMAConversation *conv = [_conversationList objectAtIndex:indexPath.row];
    [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id<IMAConversationShowAble> convable = [_conversationList objectAtIndex:indexPath.row];
    ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    IMAConversation *conv = (IMAConversation *)convable; // [self.contactMgr getUserByGroupId:receiver]
    
    switch ([convable conversationType])
    {
        case IMA_C2C:
        case IMA_Group:
        {
            IMAUser *user = [[IMAPlatform sharedInstance] getReceiverOf:conv];
            
            if (user)
            {   
//                [[AXAppDelegate sharedAppDelegate] pushToChatViewControllerWith:user];
                [self.viewModel.pushToChatView execute:user];
                
                [conv setReadAllMsg];
                
                [cell refreshCell];
            }
            else
            {
                if ([conv type] == TIM_C2C)
                {
                    // 与陌生人聊天 [IMAPlatform sharedInstance]
                    [[IMAPlatform sharedInstance] asyncGetStrangerInfo:[conv receiver] succ:^(IMAUser *auser) {
                           [self.viewModel.pushToChatView execute:auser];
                            [conv setReadAllMsg];
                            
                            ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                            [cell refreshCell];
                        
                    } fail:^(int code, NSString *msg) {
                            DebugLog(@"Fail:--> code=%d,msg=%@,fun=%s", code, msg,__func__);
//                            [[HUDHelper sharedInstance] tipMessage:IMALocalizedError(code, msg)];
                            [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
                    }];
                }
                else if ([conv type] == TIM_GROUP)
                {
                    // 有可能是因为退群本地信息信息未同步
                    [[IMAPlatform sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
                }
                
            }
        }
            break;
            
        case IMA_Sys_NewFriend:
        {
            [conv setReadAllMsg];
            [cell refreshCell];
            [IMAPlatform sharedInstance].contactMgr.hasNewDependency = NO;
            
//            FutureFriendsViewController *vc = [[FutureFriendsViewController alloc] init:YES];
//            [[AppDelegate sharedAppDelegate] pushViewController:vc];
        }
            break;
            
        case IMA_Sys_GroupTip:
        {
            [conv setReadAllMsg];
            [cell refreshCell];
            [IMAPlatform sharedInstance].contactMgr.hasNewDependency = NO;
//            GroupSystemMsgViewController *vc = [[GroupSystemMsgViewController alloc] init];
//            [[AppDelegate sharedAppDelegate] pushViewController:vc];
        }
            break;
            
        case IMA_Connect:
        default:
            break;
    }
    
}


@end
